package pers.cz.logtail;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pers.cz.config.JefConfiguration;
import pers.cz.logtail.annotation.AutoRegistServiceManager;
import pers.cz.logtail.annotation.AutoRegisterManager;
import pers.cz.logtail.config.RegeditTypeEnum;
import pers.cz.logtail.config.RegisterConfigEnum;
import pers.cz.logtail.handle.LogHandle;
import pers.cz.logtail.handle.adapter.LogSave;
import pers.cz.logtail.enums.SavePlanEnum;
import pers.cz.logtail.regedit.ServiceRegedit;
import pers.cz.netty.TcpNettyServer;
import pers.cz.netty.UdpNettyServer;
import pers.cz.netty.config.ServerNettyConfigItem;
import pers.cz.util.NetUtils;

/**
 * @program: PostGirl-panent
 * @description: 服务端启动类
 * @author: Cheng Zhi
 * @create: 2022-10-05 12:20
 **/
public class ServerApplication {

    public static Logger logger = LoggerFactory.getLogger(ServerApplication.class);

    public static final String SERVER_NAME = "LOGTAILSERVER";

    public static void main(String[] args) {

        init();

        registeService();

        // 初始化日志处理器
        LogHandle logHandle = new LogHandle();


        String savePlan = JefConfiguration.get(ServerNettyConfigItem.SAVE_PLAN);
        logger.info("当前存储策略为：" + savePlan);
        LogSave logSave = SavePlanEnum.getLogSaveInstance(savePlan);
        logHandle.setLogSavePlan(logSave);
        int port = JefConfiguration.getInt(ServerNettyConfigItem.SERVER_PORT, 4567);
        logger.info("当前使用端口：" + port);

        // 启动服务
        if ("UDP".equalsIgnoreCase(JefConfiguration.get(ServerNettyConfigItem.SERVER_COMM_TYPE, "TCP"))) {
            new UdpNettyServer(port).start(logHandle);
        } else {
            new TcpNettyServer(port).start(logHandle);
        }
    }

    private static void init() {
        // 初始化注册存储计划
        new AutoRegisterManager().registe();
        // 自动添加注册中心
        new AutoRegistServiceManager().registe();
    }

    /**
     * 把当前服务地址注册到注册中心
     */
    private static void registeService()  {
        try {
            String registerType = JefConfiguration.get(RegisterConfigEnum.REGISTER_TYPE);
            logger.info("当前使用的注册中心为：" + registerType);
            ServiceRegedit serviceRegeditInstance = RegeditTypeEnum.getServiceRegeditInstance(registerType);
            int port = JefConfiguration.getInt(ServerNettyConfigItem.SERVER_PORT, 4567);
            String ip = NetUtils.getLocalIp();
            serviceRegeditInstance.registe(SERVER_NAME, ip + ":" + port);
        } catch (Exception e) {
            logger.error("注册服务到注册中心失败，服务任正常提供！", e);
        }
    }
}
